import { Input, View } from "@tarojs/components";
import { useState } from "react";
import { ClosedEye, EyeOutlined } from "@taroify/icons";
import { Countdown } from "@taroify/core";

interface InputProps {
  placeholder?: string; // 占位符
  type?: "code" | "text" | "password";
  right?: React.ReactNode; // 右侧插��
  left?: React.ReactNode; // 左侧插��
  getCode?: () => Promise<boolean>;
  change: (value: string) => void; // 父组件的change方法
  onBlur?: () => void;
}

export default ({
  placeholder = "请输入",
  right,
  left,
  type = "text",
  getCode,
  change,
  onBlur,
}: InputProps) => {
  const [inputValue, setInputValue] = useState("");

  const handleInputChange = (e) => {
    setInputValue(e.target.value); // 更新输入值
    change(e.target.value);
  };
  const [showPwd, setShowPwd] = useState(type == "password");
  const [showCountDown, setShowCountDown] = useState(false);

  const togglePwd = () => setShowPwd((prev) => !prev);
  async function setCountDown() {
    if (getCode) {
      const flag = await getCode(); // 获取验证码
      if (flag) {
        setShowCountDown(true);
        setTimeout(() => {
          setShowCountDown(false);
        }, 60 * 1000);
      }
    }
  }
  return (
    <View className="bg-[#F2F5FA] flex-nowrap rounded flex  py-2 px-3 justify-between items-center">
      {left && <View className="mr-2 flex">{left}</View>} {/* 左侧插槽 */}
      <Input
        className="flex-grow"
        value={inputValue} // 绑定输入值
        placeholder={placeholder}
        onInput={handleInputChange} // 绑定输入变化方法
        type={showPwd ? "safe-password" : "text"} // 设置为密码或文本
        password={showPwd}
        onBlur={onBlur}
      ></Input>
      {right && <View className="ml-2">{right}</View>}
      {type == "code" &&
        (showCountDown ? (
          <Countdown value={60 * 1000}>
            {(current) => (
              <View className="flex text-[#73D0EF] text-xs">
                <View>{current.seconds}</View> 秒后可获取
              </View>
            )}
          </Countdown>
        ) : (
          <View onClick={setCountDown} className="text-[#73D0EF] text-xs ">
            获取验证码
          </View>
        ))}
      {type == "password" && (
        <View onClick={togglePwd} style={{ cursor: "pointer" }}>
          {showPwd ? <ClosedEye size={24} /> : <EyeOutlined size={24} />}
        </View>
      )}
    </View>
  );
};
